import {get} from '../assets/api/api.js'
import Vue from 'vue'
import Vuex from 'vuex'
import SockJS from 'sockjs-client'
import Stomp from 'stompjs' 
import { Notification } from 'element-ui';


Vue.use(Vuex)
const now = new Date();
const store = new Vuex.Store({
  state: {
    routes: [],
    sessions: [],
    admins: [],
    currentAdmin: null,
    currentSession: null,
    filterKey:'',
    stomp: null,
    idDot: {},
  },
  mutations: {
    INIT_CURRENTAdmin(state,currentAdmin){
      state.currentAdmin = currentAdmin;
    },
    INIT_CURRENTAdmin(state ,currentAdmin){
      
      state.currentAdmin = currentAdmin;
    },
    setRoutes(state, routes) {
      state.routes = routes;
    },
    changeCurrentSession (state,currentSession) {
			state.currentSession = currentSession;
      Vue.set(state.idDot, state.currentAdmin.username + '#' + state.currentSession.username, false);
		},
		addMessage (state,msg) {
      var mss = state.sessions[state.currentAdmin.username + "#" +msg.to];
      if(!mss){
        // state.sessions[state.currentAdmin.username + "->" +msg.to] = [];
        Vue.set(state.sessions, state.currentAdmin.username + '#' + msg.to, []);
      }
      state.sessions[state.currentAdmin.username + "#" +msg.to].push({
                content:msg.content,
                date: new Date(),
                self: !msg.isSelf,
              })
    },
    INIT_DATA (state) {
      let data = localStorage.getItem('vue-chat-session');
      
      if (data) {
        state.sessions = JSON.parse(data);
      }
    },
    INIT_ADMIN (state,data) {
      state.admins = data;
    },

  },
  actions:{

    connect(context){
      context.state.stomp = Stomp.over(new SockJS('/ws/ep'));
      let token = window.sessionStorage.getItem('tokenStr');
      context.state.stomp.connect({'Auth-Token': token}, success => {
        context.state.stomp.subscribe('/user/queue/chat', msg => {
          var receiveMessage = JSON.parse(msg.body);

          if(!context.state.currentAdmin || receiveMessage.from != context.state.currentSession.username){
            // console.log(receiveMessage.from + "->" + context.state.currentAdmin.username);
            Notification.info({
              title: '【'+receiveMessage.formNickName+'】发来一条信息',
              message: receiveMessage.content.length > 10 ? receiveMessage.content.substring(0,10) + '...' : receiveMessage.content,
              position: 'bottom-right',
            });
            Vue.set(context.state.idDot, context.state.currentAdmin.username + '#' + receiveMessage.from, true);
          }
          receiveMessage.isSelf = true;
          receiveMessage.to = receiveMessage.from;
          context.commit('addMessage',receiveMessage);
        })
      },error => {

      })
    }, 
    initData (context) {
      // context.commit('INIT_DATA');
      get('/chat/admin').then(res => {
        if(res){
          context.commit('INIT_ADMIN',res);
        }
      })

    }
	},

  
})
store.watch(function (state) {
  return state.sessions
},function (val) {
  // console.log('CHANGE: ', val);
  var object = new Object();

  console.log(object);
  localStorage.setItem('vue-chat-session', JSON.stringify(object));
},{
  deep:true/*这个貌似是开启watch监测的判断,官方说明也比较模糊*/
})


export default store;
